﻿using Newtonsoft.Json;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Hangfire.HttpJob.CSRedis
{
    /// <summary>
    /// http job 调用注册
    /// </summary>
    internal class HttpJobInvoker
    {
        readonly IHttpClientFactory _httpClientFactory;

        /// <summary>
        /// ctor
        /// </summary>
        public HttpJobInvoker(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        /// <summary>
        /// 执行作业
        /// </summary>
        /// <param name="context">作业上下文</param>
        public async Task<string> ExecuteAsync(HttpJobContext context)
        {
            var client = _httpClientFactory.CreateClient();
            client.DefaultRequestHeaders.Clear();
            if (context.Header?.Any() == true)
                foreach (var item in context.Header)
                    client.DefaultRequestHeaders.Add(item.Key, item.Value);
            var httpMethod = context.HttpMethod.ToUpperInvariant() == "POST" ? HttpMethod.Post : HttpMethod.Get;
            var reqMessage = new HttpRequestMessage(httpMethod, context.Url);
            if (httpMethod.Method == "POST" && context.JobData?.Any() == true)
                reqMessage.Content = new StringContent(JsonConvert.SerializeObject(context.JobData), Encoding.UTF8, "application/json");
            var repMessage = await client.SendAsync(reqMessage);
            return await repMessage.Content.ReadAsStringAsync();
        }
    }
}
